/* eslint-disable */
import { Input, Button, message, Switch, Form } from 'antd'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { Config } from '@/services/features/new-rank'
import './Content.module.less'

const patternRule = {
  async validator(rule: unknown, value: string) {
    try {
      new RegExp(value)
    } catch (e) {
      return Promise.reject(new Error('正则表达式不合法'))
    }
  },
}

export default function Content(props: { onClose: () => void }) {
  const { onClose } = props
  const [config] = useStreams(services.features.newRank.config)

  const [saving, setSaving] = useState(false)
  async function save(values: Config) {
    setSaving(true)
    const res = await services.features.newRank.saveConfig(values)
    setSaving(false)
    if (res.success) onClose()
    else void message.warning('保存失败：' + res.error)
  }

  return <Form
    styleName="content"
    labelCol={{ span: 6 }}
    initialValues={config ?? { enable: false, idPattern: '' }}
    onFinish={save}
  >
    <Form.Item label="新榜数据" name="enable" valuePropName="checked">
      <Switch disabled={!config} checkedChildren="开启" unCheckedChildren="关闭" />
    </Form.Item>
    <Form.Item
      label="公众号ID提取正则"
      name="idPattern"
      extra="请输入用于提取公众号ID（以 gh_ 开头）的正则表达式"
      rules={[{ required: true }, patternRule]}
    >
      <Input disabled={!config} maxLength={100} />
    </Form.Item>
    <Form.Item wrapperCol={{ offset: 6 }}>
      <Button loading={saving} type="primary" htmlType="submit">
        保存
      </Button>
    </Form.Item>
  </Form>
}
